package com.seleniti.enpareja.android.ui.widget;

import org.ioc.commons.ui.features.Info;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import com.seleniti.enpareja.android.R;

public class InfoInlineWidget extends TextView implements Info {

	private InfoType type;
	private boolean autoDisplay;

	public InfoInlineWidget(Context context) {
		super(context);
	}

	public InfoInlineWidget(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public InfoInlineWidget(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		if (!isInEditMode()) {
			TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.InfoInlineWidget);
			CharSequence text = a.getString(R.styleable.InfoInlineWidget_text);
			if (text != null) {
				this.setText(text);
			}
			boolean visible = a.getBoolean(R.styleable.InfoInlineWidget_visible, this.isVisible());
			boolean autoDisplay = a.getBoolean(R.styleable.InfoInlineWidget_autoDisplay, this.autoDisplay);
			String typeString = a.getString(R.styleable.InfoInlineWidget_type);
			this.setVisible(visible);
			this.setType(typeString != null && !typeString.isEmpty() ? InfoType.valueOf(typeString) : InfoType.WARNING);
			this.setAutoDisplay(autoDisplay);
			a.recycle();
		}
	}

	@Override
	public void setType(InfoType infoType) {
		this.type = infoType;
		if (!isInEditMode()) {
			switch (this.type) {
			case ERROR:
				this.setCompoundDrawablesWithIntrinsicBounds(R.drawable.error16x16, 0, 0, 0);
				break;
			case INFO:
				this.setCompoundDrawablesWithIntrinsicBounds(R.drawable.info_icon, 0, 0, 0);
				break;
			case OPERATION_OK:
				this.setCompoundDrawablesWithIntrinsicBounds(R.drawable.tick16x16, 0, 0, 0);
				break;
			case WARNING:
				this.setCompoundDrawablesWithIntrinsicBounds(R.drawable.alert_icon, 0, 0, 0);
				break;
			}
		}
	}

	@Override
	public void setText(String text) {
		super.setText(text);
		if (!isInEditMode()) {
			if (this.autoDisplay) {
				setVisible(text != null && !text.isEmpty());
			}
		}
	}

	@Override
	public String getText() {
		CharSequence text = super.getText();
		return text != null ? text.toString() : null;
	}

	@Override
	public InfoType getType() {
		return this.type;
	}

	@Override
	public void setVisible(boolean visible) {
		if (!isInEditMode()) {
			this.setVisibility(visible ? View.VISIBLE : View.GONE);
		}
	}

	@Override
	public boolean isVisible() {
		return this.getVisibility() == View.VISIBLE;
	}

	public boolean isAutoDisplay() {
		return autoDisplay;
	}

	public void setAutoDisplay(boolean autoDisplay) {
		this.autoDisplay = autoDisplay;
	}
}
